// 用户相关仓库

// 导入Cookie,存储Token
import { setToken, getToken, removeToken } from '../../utils/auth'
// 登录API
import { loginAPI, getUserInfoAPI, logoutAPI } from '../../api/login'

const user = {
  state: {
    // 存储Token
    token: getToken(),
    // 存储用户信息
    roles: [],
    permissions: [],
    name: '', // 用户名字
    avatar: '' // 用户头像信息
  },

  mutations: {
    // 存储Token方法
    SET_TOKEN (state, token) {
      state.token = token
    },

    // 存储用户信息方法
    SET_ROLES (state, roles) {
      state.roles = roles
    },

    //
    SET_PERMISSIONS (state, permissions) {
      state.permissions = permissions
    },

    // 存储用户名字
    SET_NAME: (state, name) => {
      state.name = name
    },

    // 存储用户头像
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    }
  },

  actions: {
    registerLogin ({ commit }, userInfo) {
      // // 调用接口
      // const res = await loginAPI(
      //   userInfo.username.trim(), userInfo.password, userInfo.code, userInfo.uuid
      // )
      // console.log('登录成功', res)
      // commit('SET_TOKEN', res.token)

      return new Promise((resolve, reject) => {
        // 调用接口
        loginAPI(
          userInfo.username.trim(), userInfo.password, userInfo.code, userInfo.uuid
        ).then(res => {
          // 持久化存储Token
          setToken(res.token)
          // 拿到接口返回值 , 存储Token
          commit('SET_TOKEN', res.token)
          // 抛出成功
          resolve(res)
          // 铺货错误
        }).catch(error => {
          // 抛出错误
          reject(error)
        })
      })
    },

    // 获取用户信息
    getUserInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        getUserInfoAPI().then(res => {
          // 拿到头像信息
          const avatar = (res.user.avatar === '' || user.avatar === null)
            ? require('@/assets/images/profile.jpg') : process.env.VUE_APP_BASE_URL + user.avatar

          if (res.roles && res.roles.length > 0) {
            commit('SET_ROLES', res.roles)
            commit('SET_PERMISSIONS', res.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          // 存储用户信息
          commit('SET_NAME', user.username)
          commit('SET_AVATAR', avatar)
          // 抛出成功
          resolve(res)
        }).catch(error => {
          // 抛出错误
          reject(error)
        })
      })
    },

    // Token失效重新登录
    logOut ({ commit }, state) {
      return new Promise((resolve, reject) => {
        // 调用退出登录API
        logoutAPI().then(() => {
          // 调用设置Token方法  , 将Token传递的传参为空 , 设置Token为空
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          // 清除Token
          removeToken()
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    }
  }
}

export default user
